package com.bitcat.firstapp.demo.netdemo

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.bitcat.firstapp.R
import com.bitcat.firstapp.databinding.ActivityNetDemoBinding
import com.google.gson.Gson
import es.dmoral.toasty.Toasty
import okhttp3.Call
import okhttp3.Callback
import okhttp3.FormBody
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import java.io.IOException
import kotlin.concurrent.thread

class NetDemoActivity : AppCompatActivity() {

    private lateinit var binding: ActivityNetDemoBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityNetDemoBinding.inflate(layoutInflater)
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
    }

    // get同步请求
    fun request1(view: View) {
        thread {
            try {// 1. 创建 OkHttpClient 对象
                val client = OkHttpClient()

                //2. 创建 Request 对象
                val request = Request.Builder()
                    .url("https://www.baidu.com")
                    .build()

                //3. 发送请求，获取响应结果
                val response = client.newCall(request).execute()
                response.use {
                    //服务端正常响应
                    if (response.isSuccessful) {
                        val result = response.body?.string()
//             result = response.body?.string() //报错：IllegalStateException: closed


                        //这里还是处于子线程
                        runOnUiThread {
                            binding.contentTv.text = result
                        }
                    } else {
                        Log.e("请求失败", response.message)
                    }
                }


            } catch (e: Exception) {
                e.message?.let { Log.e("请求失败", it) }
            }

        }

    }

    // get异步请求
    fun request2(view: View) {

        try {// 1. 创建 OkHttpClient 对象
            val client = OkHttpClient()

            //2. 创建 Request 对象
            val request = Request.Builder()
                .url("https://www.baidu.com")
                .build()

            //3. 发送请求，获取响应结果
            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    e.message?.let { Log.e("请求失败", it) }
                }

                override fun onResponse(call: Call, response: Response) {
                    response.use {
                        //服务端正常响应
                        if (response.isSuccessful) {
                            val result = response.body?.string()
//             result = response.body?.string() //报错：IllegalStateException: closed
                            //这里还是处于子线程
                            runOnUiThread {
                                binding.contentTv.text = result
                            }
                        } else {
                            Log.e("请求失败", response.message)
                        }
                    }
                }
            })
        } catch (e: Exception) {
            e.message?.let { Log.e("请求失败", it) }
        }


    }

    fun request3(view: View) {
        try {

            //0. 创建日志拦截器
            val loggingInterceptor = HttpLoggingInterceptor()
            loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY


            // 1. 创建 OkHttpClient 对象
            val client = OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .build()

            //2. 创建 Request 对象
            val request = Request.Builder()
                .url("https://v.api.aa1.cn/api/zhihu-news/")
                .build()

            //3. 发送请求，获取响应结果
            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    e.message?.let { Log.e("请求失败", it) }
                }

                override fun onResponse(call: Call, response: Response) {
                    response.use {
                        //服务端正常响应
                        if (response.isSuccessful) {
                            val result = response.body?.string()
//             result = response.body?.string() //报错：IllegalStateException: closed
                            //这里还是处于子线程
                            runOnUiThread {
//                                binding.contentTv.text = result
                                val newsBean = Gson().fromJson(result, NewsBean::class.java)
                                Toasty.info(this@NetDemoActivity, newsBean.news[0].title).show()
                            }
                        } else {
                            Log.e("请求失败", response.message)
                        }
                    }
                }
            })
        } catch (e: Exception) {
            e.message?.let { Log.e("请求失败", it) }
        }
    }

    fun request4(view: View) {
        try {

            //0. 创建日志拦截器
            val loggingInterceptor = HttpLoggingInterceptor()
            loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY


            // 1. 创建 OkHttpClient 对象
            val client = OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .build()

            //2. 创建 Request 对象
            val request = Request.Builder()
                .url("http://10.0.2.2:8081/user/hello") //自带的模拟器
//                .url("https://192.168.1.3:8081/user/hello") //自带的模拟器
                .build()

            //3. 发送请求，获取响应结果
            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    e.message?.let { Log.e("请求失败", it) }
                }

                override fun onResponse(call: Call, response: Response) {
                    response.use {
                        //服务端正常响应
                        if (response.isSuccessful) {
                            val result = response.body?.string()
//             result = response.body?.string() //报错：IllegalStateException: closed
                            //这里还是处于子线程
                            runOnUiThread {
                                binding.contentTv.text = result
//                                val newsBean = Gson().fromJson(result, NewsBean::class.java)
//                                Toasty.info(this@NetDemoActivity, newsBean.news[0].title).show()
                            }
                        } else {
                            Log.e("请求失败", response.message)
                        }
                    }
                }
            })
        } catch (e: Exception) {
            e.message?.let { Log.e("请求失败", it) }
        }
    }

    fun request5(view: View) {
        //1. 创建okhttpClient对象
        val client = OkHttpClient()

        //2. 创建表单请求对象
        val formBody = FormBody.Builder()
            .add("username", "admin")
            .add("password", "123456")
            .build()

        //3. 创建请求对象
        val request = Request.Builder()
            .url("http://10.0.2.2:8081/user/login")
            .post(formBody)
            .build()

        //4. 发送请求，获取响应结果
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                e.message?.let { Log.e("请求失败", it) }
            }

            override fun onResponse(call: Call, response: Response) {
                response.use {
                    if (response.isSuccessful) {
                        val result = response.body?.string()
                        runOnUiThread {
                            binding.contentTv.text = result
                        }
                    }
                }
            }
        })
    }


    //提交JSON数据
    fun request6(view: View) {
        //1. 创建okhttpClient对象
        val client = OkHttpClient()

        //2. 构建JSON请求数据
//        val json = """
//            {
//                "username": "admin",
//                "password": "123456"
//            }
//        """
        val user = User("admin", "666666")
        val json = Gson().toJson(user)

        val mediaType = "application/json".toMediaType()
        val requestBody = json.toRequestBody(mediaType)

        //3. 创建请求对象
        val request = Request.Builder()
            .url("http://10.0.2.2:8081/user/login2")
            .post(requestBody)
            .build()

        //4. 发送请求，获取响应结果
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                e.message?.let { Log.e("请求失败", it) }
            }

            override fun onResponse(call: Call, response: Response) {
                response.use {
                    if (response.isSuccessful) {
                        val result = response.body?.string()
                        runOnUiThread {
                            binding.contentTv.text = result
                        }
                    }
                }
            }
        })
    }

    fun request7(view: View) {
        RetrofitClient.newsApi.getNews().enqueue(object :retrofit2.Callback<NewsBean>{
            override fun onResponse(
                call: retrofit2.Call<NewsBean>,
                response: retrofit2.Response<NewsBean>
            ) {
               val newsBean = response.body()
                if (newsBean != null) {
                    val newsText = buildString {
                        append("日期:${newsBean.date}\n")
                        newsBean.news.take(3).forEach {
                            append("标题:${it.title}\n")
                        }
                    }
                    binding.contentTv.text = newsText
                }
            }

            override fun onFailure(call: retrofit2.Call<NewsBean>, t: Throwable) {
                t.printStackTrace()
                Toasty.error(this@NetDemoActivity, "请求失败").show()
            }
        })
    }

    fun request8(view: View) {
        RetrofitClient.newsApi.loginForm("admin","111111").enqueue(object :retrofit2.Callback<Any>{
            override fun onResponse(
                call: retrofit2.Call<Any>,
                response: retrofit2.Response<Any>
            ) {
                val result = response.body().toString()
                binding.contentTv.text = result
            }

            override fun onFailure(call: retrofit2.Call<Any>, t: Throwable) {
                t.printStackTrace()
                Toasty.error(this@NetDemoActivity, "请求失败").show()
            }
        })
    }
    fun request9(view: View) {
        val user = User("admin","12345")
        RetrofitClient.newsApi.loginJson(user).enqueue(object :retrofit2.Callback<Any>{
            override fun onResponse(
                call: retrofit2.Call<Any>,
                response: retrofit2.Response<Any>
            ) {
                val result = response.body().toString()
                binding.contentTv.text = result
            }

            override fun onFailure(call: retrofit2.Call<Any>, t: Throwable) {
                t.printStackTrace()
                Toasty.error(this@NetDemoActivity, "请求失败").show()
            }
        })
    }
}

data class User(
    val username:String,
    val password:String
)